#pragma once
#include <pthread.h>

#define DEFAULT_TIME 10                      //领导定时检查队列、线程状态的时间间隔
#define MIN_WAIT_TASK_NUM 10      //队列中等待的任务数 > 这个值, 便会增加线程
#define DEFAULT_THREAD_VARY 10   //每次线程加减的数目

#define false 0
#define true 1

typedef struct _threadpool_task{
    /*函数指针,回调函数*/
    void* (*function)(void*);
    /*上面函数的参数*/
    void* arg;
}threadpool_task_t; /*各子线程任务结构体*/

/*描述线程池相关信息*/
typedef struct _threadpool {
    pthread_mutex_t lock;                                       /*用于锁住本结构体*/    
    pthread_mutex_t thread_counter;               /*记录忙状态线程个数的锁 -- busy_thr_num*/
    pthread_cond_t queue_not_full;                  /*当任务队列满时,添加任务的线程阻塞,等待在此条件变量*/
    pthread_cond_t queue_not_empty;         /*任务队列里不为空,通知等待任务的线程*/

    pthread_t* threads;                                             /*存放线程池中每个线程的tid。数组*/
    pthread_t adjust_tid;                                          /*存管理线程tid*/
    threadpool_task_t* task_queue;                  /*任务队列*/

    int min_thr_num;                                                /*线程池最小线程个数*/
    int max_thr_num;                                                /*线程池最大线程个数*/
    int live_thr_num;                                                  /*当前存活的线程个数*/
    int busy_thr_num;                                               /*忙状态线程个数*/
    int wait_exit_thr_num;                                      /*要销毁的线程个数*/

    int queue_front;                                                    /*task_queue队头下标*/
    int queue_rear;                                                     /*task_queue队尾下标*/
    int queue_size;                                                     /*task_queue队列中实际任务数量*/
    int queue_max_size;                                         /*task_queue队列可容纳任务数上线*/

    int shutdown;                                                       /*标志位,线程池使用状态, true 或false*/
}threadpool_t;

threadpool_t* threadpool_create(int min_thr_num, int max_thr_num, int queue_max_size);
int threadpool_free(threadpool_t* pool);
void* threadpool_thread(void* threadpool);
void* adjust_thread(void* threadpool);
int is_thread_alive(pthread_t tid);
int threadpool_add(threadpool_t* pool, void*(*function)(void* arg), void* arg);
int threadpool_destroy(threadpool_t* pool);